<template>
  <div class="file-add sub-margin">
    <div class="sub-page-title sub-page-return">
      <el-button size="small" icon="el-icon-arrow-left" @click.stop="returnPage">返回</el-button>
      {{ id ? '编辑' : '添加' }}{{ type === '4' ? '制度文件' : '工作通知' }}
    </div>
    <div class="content">
      <el-scrollbar class="main_con">
        <el-form :model="form" :rules="rules" ref="ruleForm" size="medium" label-width="90px" class="notice_form">
          <div class="form_title">基本信息</div>

          <el-form-item label="标题" prop="bulletinTitle">
            <el-input placeholder="请输入" v-model="form.bulletinTitle"></el-input>
          </el-form-item>
          <el-form-item label="来源" prop="source">
            <el-input placeholder="请输入" v-model="form.source"></el-input>
          </el-form-item>
          <div class="form_title">详细内容</div>
          <el-form-item label="内容" prop="bulletinContent">
            <TinymceEditor
              class="replayCont"
              v-model="form.bulletinContent"
              v-if="tinyMcHeight"
              :height="tinyMcHeight"
              use-in-report></TinymceEditor>
          </el-form-item>
          <el-form-item label="附件">
            <UploadFile :showLabel="false" :file-list="enclosureList" businessType="notice">
              <el-form-item
                label="是否允许下载"
                prop="isDownfile"
                slot="other"
                class="marBottom0 marLeft10"
                label-width="100px">
                <el-switch v-model="form.isDownfile"></el-switch>
              </el-form-item>
            </UploadFile>
          </el-form-item>
          <el-form-item label="公开范围" prop="scopeOpenChoose">
            <el-cascader
              class="selectStyle"
              placeholder="请选择"
              :options="orgOptions"
              :props="{ multiple: true, label: 'orgName', children: 'queryOutVOS', value: 'id', emitPath: false }"
              filterable
              v-model="form.scopeOpenChoose"
              @change="onSelectChange"
              ref="cascader"
              :show-all-levels="false"></el-cascader>
          </el-form-item>
          <el-row>
            <el-col :span="4">
              <el-form-item label="是否置顶" prop="isTop">
                <el-switch active-color="#004db6" v-model="form.isTop"></el-switch>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="18">
              <el-form-item label="是否短信通知" prop="isSendmsg" label-width="100px">
                <el-switch active-color="#004db6" v-model="form.isSendmsg"></el-switch>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-form-item>
            <el-button class="btnBg" type="primary" @click="setData('ruleForm', 1)">发布</el-button>
            <!-- :disabled="form.status == 1" -->
            <el-button class="btnBg" type="primary" @click="setData('ruleForm', 0)">暂存</el-button>
            <el-button class="btnBorder" plain @click="onPreview">预览</el-button>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import TinymceEditor from '@com/TinymceEditor.vue'
import UploadFile from '@com/UploadFile'
import { addBulletion, getBulletionDetail } from '@apis/notice.js'
import { listOrganByTenantId } from '@apis/common.js'
import { cloneDeep } from 'lodash'
export default {
  name: 'fileAdd',
  components: { TinymceEditor, UploadFile },
  props: {},
  data() {
    return {
      id: '',
      type: '',
      orgOptions: [],
      enclosureList: [],
      form: {
        bulletinContent: '',
        isDownfile: true,
        isTop: false,
        isSendmsg: false,
        fileShowVOS: [],
        scopeOpen: [],
        scopeOpenChoose: [],
        status: '',
        type: '0', // 默认为0；类型：0为工作通知 1为暂定为公告
        isAllPublic: '',
      },
      rules: {
        bulletinTitle: [
          {
            required: true,
            message: '标题不能为空',
            trigger: 'blur',
          },
        ],
        scopeOpenChoose: [
          {
            required: true,
            message: '请选择公开范围',
            trigger: 'blur',
          },
        ],
        desc: [
          {
            required: true,
            message: '请填写活动形式',
            trigger: 'blur',
          },
        ],
      },
      tinyMcHeight: 400,
    }
  },
  watch: {},
  computed: {},
  created() {
    const { id, type } = this.$route.params
    this.id = id || ''
    this.type = type || ''
  },
  mounted() {
    this.setDataInit()

    this.initOrgData()

    const data = sessionStorage.getItem('noticePreviewData')
      ? JSON.parse(sessionStorage.getItem('noticePreviewData'))
      : {}
    if (sessionStorage.getItem('noticePreviewData')) {
      this.form = { ...data }
      this.enclosureList = [...data.fileShowVOS]
    } else {
      if (this.id) {
        this.initdata()
        this.$set(this.form, 'id', this.id)
      }
    }
  },
  methods: {
    returnPage() {
      this.$router.go(-1)
    },
    /* 监听选择 */
    onSelectChange(e) {
      if (!e) return
      console.log('e :>> ', e)
      this.$forceUpdate()
    },
    /* 处理数据 */
    setData(formName, status) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const fromData = cloneDeep(this.form)
          fromData.isDownfile = this.form.isDownfile ? 1 : 0
          fromData.isTop = this.form.isTop ? 1 : 0
          fromData.isSendmsg = this.form.isSendmsg ? 1 : 0
          this.$set(fromData, 'status', status)
          this.$set(fromData, 'fileShowVOS', this.enclosureList)
          this.$set(fromData, 'scopeOpen', [])
          if (this.form.scopeOpenChoose) {
            const obj = { orgId: '', type: '' }
            for (let i = 0; i < this.form.scopeOpenChoose.length; i++) {
              if (this.form.scopeOpenChoose[i][1]) {
                const dataObj = Object.assign({}, obj)
                dataObj.orgId = this.form.scopeOpenChoose[i][1]
                fromData.scopeOpen.push(dataObj)
              }
            }
          }
          this.submitData(status, fromData)
        } else {
          return false
        }
      })
    },
    onPreview() {
      this.$set(this.form, 'fileShowVOS', this.enclosureList)
      sessionStorage.setItem('noticePreviewData', JSON.stringify(this.form))
      this.$router.push({
        name: 'PSKH_SYSTEM_FILE_DETAIL',
        params: { type: this.indType },
      })
    },
    setDataInit() {
      this.form.type = this.type
      this.form.scopeOpenChoose = []
    },
    /* 提交数据 */
    submitData(status, fromData) {
      addBulletion({
        ...fromData,
      }).then(res => {
        if (res.status === 200) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '回到列表',
            cancelButtonText: '继续添加',
            type: 'success',
          })
            .then(() => {
              this.$router.go(-1)
            })
            .catch(() => {
              this.form = {
                bulletinContent: '',
                isDownfile: true,
                isTop: false,
                isSendmsg: false,
                fileShowVOS: [],
                scopeOpen: [],
                scopeOpenChoose: [],
                status: '',
                type: this.type,
                isAllPublic: '',
              }
              this.setDataInit()
              this.enclosureList = []
            })
          // if (status === 0) {
          //   this.$message.success('暂存成功')
          // } else {

          // }
        }
      })
    },
    initOrgData() {
      /* 查询公开范围的机构数据 */
      listOrganByTenantId().then(res => {
        const options = [
          {
            id: '123',
            nextNums: null,
            orgName: '全部',
            pid: null,
            queryOutVOS: res.data,
          },
        ]
        this.orgOptions = options
      })
    },
    /* 初始化数据 */
    initdata() {
      getBulletionDetail({
        bulletionId: this.id,
      }).then(res => {
        const data = res.data
        // console.log(data);
        this.form = { ...data }
        this.form.isDownfile = data.isDownfile === 1
        this.form.isTop = data.isTop === 1
        this.form.isSendmsg = data.isSendmsg === 1
        this.form.type = this.form.type.toString()
        this.$set(this.form, 'scopeOpenChoose', [])
        data.scopeOpen.forEach((item, index) => {
          this.form.scopeOpenChoose.push(item.orgId)
        })
        this.$forceUpdate()
        this.enclosureList = [...data.fileShowVOS]
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@styles/layout.scss';
.file-add {
  height: 100%;
  .content {
    flex: 1;
    display: flex;
    align-items: stretch;
    padding: 20px 80px;
    height: calc(100% - 80px);
    .main_con {
      flex: 1;
      height: calc(100% - 25px);
      .el-radio {
        margin-right: 10px;
      }
      .notice_form {
        margin: 0 auto;
        width: 100%;
        padding: 20px 30px;

        /deep/.el-form-item__label {
          font-weight: bold;
          color: #333;
        }

        /deep/.el-input {
          input {
            border-radius: 1px;
          }
        }

        /deep/.el-form-item {
          margin-bottom: 20px;
        }

        .form_title {
          font-size: 16px;
          font-weight: bold;
          padding-bottom: 10px;
          border-bottom: solid 1px #004db6;
          margin-bottom: 15px;
        }

        .selectStyle {
          width: 100%;
        }

        .marBottom0 {
          margin-bottom: 0;
        }

        .marLeft10 {
          margin-left: 35px;
        }
      }
    }
  }
}
</style>
